package com.jiuyou.websocket.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.jiuyou.websocket.enums.RequestType;
import com.jiuyou.websocket.handler.base.TalkWebSocketHandler;
import com.jiuyou.websocket.manager.WebSocketSessionManager;
import com.jiuyou.websocket.service.DisposeMessageService;
import com.jiuyou.websocket.service.LoginWebSocketService;
import com.jiuyou.websocket.util.ResponseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

/**
 * WebSocket 对话消息处理器
 */

@Service
public class TalkMessageHandler extends TalkWebSocketHandler {

    private final Logger log = LoggerFactory.getLogger(TalkMessageHandler.class);

    @Autowired
    private WebSocketSessionManager wsSessionManager;

    @Autowired
    private LoginWebSocketService loginWebSocketService;

    @Autowired
    private DisposeMessageService disposeMessageService;

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        super.handleTextMessage(session, message);
        String textMsg = message.getPayload();
        //处理消息
        disposeMessageRequest(textMsg, session);
    }

    /**
     * 处理消息
     * @param message
     * @param wsSession
     */
    private void disposeMessageRequest(String message, WebSocketSession wsSession) {
        JSONObject jsonObject = null;
        try {
            jsonObject = JSON.parseObject(message);
            String reqType = jsonObject.getString("reqType");

            if (RequestType.CHECK_HEARTBEAT.equals(reqType)) {
                //发送心跳信息
                wsSessionManager.appointSending(wsSession, message);
                return;
            }

            log.info("接收到消息：{}", message);

            //更新用户信息
            boolean b = loginWebSocketService.updateUserInfo(wsSession);
            if (!b) {
                return;
            }

            JSONObject jsonObjParam = jsonObject.getJSONObject("reqParam");
            JSONObject jsonInfo = null;
            switch (RequestType.getIfPresent(reqType)) {
                case MY_MSG_UNREAD_COUNT:
                    //获取我的未读消息数量
                    jsonInfo = disposeMessageService.getMyMsgUnreadCount(jsonObjParam,wsSession);
                    break;
                case MY_MSG_LIST:
                    //获取我的消息列表
                    jsonInfo = disposeMessageService.getMyMsgList(jsonObjParam, wsSession);
                    break;
                case DIALOG_BY_LIST:
                    //获取与某人的对话列表倒序分页
                    jsonInfo = disposeMessageService.getDialogByList(jsonObjParam, wsSession);
                    break;
                case UPDATE_READ_STATUS:
                    //将某人发给我的信息变为已读
                    jsonInfo = disposeMessageService.updateReadStatus(jsonObjParam, wsSession);
                    break;
                case SEND_MSG:
                    //给某人发消息
                    jsonInfo = disposeMessageService.sendMsg(jsonObjParam, wsSession);
                    break;
                default:
                    jsonInfo = new JSONObject();
                    jsonInfo.put("message", "此请求不存在！");
                    ResponseResult.toJSONObjectError(jsonInfo);
                    break;
            }

            if (null == jsonInfo) {
                return;
            }

            jsonObject.remove("reqParam");
            jsonObject.put("info", jsonInfo);
        } catch (Exception e) {
            log.error("消息处理异常", e);
            jsonObject = new JSONObject();
            jsonObject.put("info", ResponseResult.toJSONObjectError());
        }

        String resultStr = JSON.toJSONString(jsonObject, SerializerFeature.WriteMapNullValue);
        wsSessionManager.appointSending(wsSession, resultStr);
    }

}
